package testProject;

import java.io.IOException;
import java.io.InputStream;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.onpositive.page.pagerendering.EditLinkRenderer;
import com.onpositive.storage.managers.UnifiedContentProvider;

public class ResourcesShowFilter implements Filter {

	private ServletContext context;

	public void destroy() {
		// TODO Auto-generated method stub

	}

	public void doFilter(ServletRequest arg0, ServletResponse arg1,
			FilterChain arg2) throws IOException, ServletException {

		HttpServletRequest hs = (HttpServletRequest) arg0;
		String localAddr = hs.getRequestURI();
		String addressInStaticFileSystem = localAddr;
		if (addressInStaticFileSystem.endsWith(EditLinkRenderer.SUFFIX)) {
			arg2.doFilter(arg0, arg1);
			return;
		}
		int flg = 0;
		if (localAddr.indexOf(UnifiedContentProvider.IMAGES_DIR) == 0) {
			addressInStaticFileSystem = localAddr
					.substring(UnifiedContentProvider.IMAGES_DIR.length());
			flg = 1;
		} else if (localAddr.indexOf(UnifiedContentProvider.RESOURCES_DIR) == 0) {
			addressInStaticFileSystem = localAddr
					.substring(UnifiedContentProvider.RESOURCES_DIR.length());
			flg = 2;
		}
		InputStream is = UnifiedContentProvider
				.getContentElementAsStream(localAddr);

		HttpServletResponse resp = (HttpServletResponse) arg1;
		if (flg == 1) {
			resp.setContentType("image");
		} else if (flg == 2) {
			resp.setContentType("text/css");
		} else {
			resp.setContentType("text/html");
		}
		ServletOutputStream sOs = resp.getOutputStream();

		byte[] buffer = new byte[1024];
		int counter = 0;
		while ((counter = is.read(buffer)) != -1) {
			sOs.write(buffer, 0, counter);
		}

		is.close();
		sOs.close();
	}

	public void init(FilterConfig arg0) throws ServletException {
		context = arg0.getServletContext();
	}

}
